/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* NOTES IMPLEMENTACIÓ JPANIMAL 02/01/14
   Per unificar criteris i millorar l'herència visual s'implementa la clase JPAnimal. 
   Consideracions a l'hora de millorar la implementació. 
   cal reviasar totes les modificacions.
   i el TDSLanguageUtils

*/


package xmarti.vacaxm.client.maintenance.animal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import xmarti.vacaxm.action.ImplMaintenance;
import xmarti.vacaxm.beans.maintenance.*;
import xmarti.vacaxm.exception.ExceptionHibernateVacaxm;
import xmarti.vacaxm.exception.ExceptionXML;
import xmarti.vacaxm.format.FormatJTableAndJSplitPane;
import xmarti.vacaxm.utils.IActionUpdate;
import xmarti.vacaxm.utils.JTableXM;
import xmarti.vacaxm.utils.TDSLanguageUtils;
import xmarti.vacaxm.utils.TableModel;
import xmarti.vacaxm.utils.UpdateAction;
import xmarti.vacaxm.utils.Utils;


/**
 *
 * @author xmarti
 */
public class JPAnimal extends javax.swing.JPanel implements IActionUpdate {    
    private ImplMaintenance aMaintenance;    
    //private FormatJSplitPane fJsplit;
    private List animals;    
    private JTableXM jTable; 
    private EnumGender gender;
    private Animal animal=null; 
    private JPAnimalData jpAnimalData; 
    private String animalClass;
    private boolean insert;
    private boolean saved; 
    private boolean onlyRead; 
    private boolean handleAction; 
    private UpdateAction actions;
    private AnimalFilter animalFilter;    
    private TableModel model = null;
    //private ListSelectionModel selectionModel=null;
    //private List<SortKey> orderTable=null;
    private FormatJTableAndJSplitPane formatPanel;
    public JPAnimal(ImplMaintenance aMaintenance,UpdateAction actions,String animalClass) {
        initComponents( ); //inicialitza tots el components
        this.animalClass= animalClass;    // guardem el tipus d'animal   
        this.aMaintenance= aMaintenance;  // gestor Hibernate
        this.actions=actions;             // guardem les accions d'inserció que es duen a terme
        this.animalFilter= new AnimalFilter();          // per construir el filtre 
        this.handleAction=true;
        this.jTable= new JTableXM() {
            @Override
            public void handleSelectionEvent(ListSelectionEvent e) {
                 selectionEvent(e);
            }
        };
        this.jScrollPaneTable.setViewportView(this.jTable);
        try {                            
            if (this.animalClass.equals(Cow.class.getName()) ) { // en el cas d'una vaca               
                this.animal= new Cow(); // l'animal serà una vaca
                this.jPanel1.setBackground(Utils.getColorCow());
                this.jPanel2.setBackground(Utils.getColorCow());
            }
            else if(this.animalClass.equals(Bull.class.getName())){ // en el cas d'un toro               
                this.animal= new Bull();            
                this.jPanel1.setBackground(Utils.getColorBull());
                this.jPanel2.setBackground(Utils.getColorBull());
            }
            chargeData(null); // carreguem les dades
            this.formatPanel= new FormatJTableAndJSplitPane(this.jSplitPane,this.jTable,this.animalClass);                      
            this.formatPanel.chargeFormat();
        }catch (ExceptionHibernateVacaxm ex) {        
            JOptionPane.showMessageDialog(null,ex.getMessage(),TDSLanguageUtils.getMessage("charge.data.ERR"),JOptionPane.ERROR_MESSAGE);
        } catch (ExceptionXML ex) {
            Logger.getLogger(JPAnimal.class.getName()).log(Level.SEVERE, null, ex);
        }          
    }
    public JPAnimal(ImplMaintenance aMaintenance,UpdateAction actions,String animalClass,EnumGender gender) {
        initComponents( );
        this.animalClass= animalClass;      
        this.aMaintenance= aMaintenance; 
        this.actions=actions; 
        this.gender=gender;
        this.jPanel1.setBackground(Utils.getColorCalf());
        this.jPanel2.setBackground(Utils.getColorCalf());
        this.animalFilter= new AnimalFilter();  
        this.handleAction=true;
        this.jTable= new JTableXM() {
            @Override
            public void handleSelectionEvent(ListSelectionEvent e) {
                 selectionEvent(e);
            }
        };
        this.jScrollPaneTable.setViewportView(this.jTable);
        try {                                       
            chargeData(null);        
            this.formatPanel= new FormatJTableAndJSplitPane(this.jSplitPane,this.jTable,this.animalClass);                      
            this.formatPanel.chargeFormat();
        }catch (ExceptionHibernateVacaxm ex) {        
            JOptionPane.showMessageDialog(null,ex.getMessage(),TDSLanguageUtils.getMessage("charge.data.ERR"),JOptionPane.ERROR_MESSAGE);
        } catch (ExceptionXML ex) {
            Logger.getLogger(JPAnimal.class.getName()).log(Level.SEVERE, null, ex);
        }          
    }
//    
    
    public void setFormat(){
        this.formatPanel.setFormat();
        try {
            this.formatPanel.saveFormat();
        } catch (ExceptionXML ex) {
            Logger.getLogger(JPAnimal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void chargeData(JPAnimalData jpAnimalData) throws ExceptionHibernateVacaxm{                        
        this.jTable.chargeModel(this.getModel());                 
        int i =this.jTable.getModel().getRowCount(); // compte els animals filtrats del total
        
        if (this.animalClass.equals(Calf.class.getName())){
            this.jLabelCount.setText(i + " "+TDSLanguageUtils.getMessage("jPanelAnimal.jLabelCount.caption.de")+" "+this.aMaintenance.getNumberAnimals(Calf.class,this.gender.getGender()));
        } else if (this.animalClass.equals(Cow.class.getName())){
            this.jLabelCount.setText(i + " "+TDSLanguageUtils.getMessage("jPanelAnimal.jLabelCount.caption.de")+" "+this.aMaintenance.getNumberAnimals(Cow.class));
        }else{
            this.jLabelCount.setText(i + " "+TDSLanguageUtils.getMessage("jPanelAnimal.jLabelCount.caption.de")+" "+this.aMaintenance.getNumberAnimals(Bull.class));
       }                
       if (jpAnimalData==null) {          //en aquest cas mostra el contenidor de les subpantalles.
            this.jPanel2.setVisible(false);
        }else{
            this.jpAnimalData=jpAnimalData;
            this.jPanel2.setVisible(true);
        }       
        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelCount1 = new javax.swing.JLabel();
        jSplitPane = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        jToolBarData = new javax.swing.JToolBar();
        jToogleButtonModify = new javax.swing.JToggleButton();
        jButtonSave = new javax.swing.JButton();
        jButtonRemove = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTabbedPane = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jToolBar2 = new javax.swing.JToolBar();
        jButtonNew = new javax.swing.JButton();
        jButtonSearch = new javax.swing.JButton();
        jToogleButtonFilter = new javax.swing.JToggleButton();
        jLabelCount = new javax.swing.JLabel();
        jScrollPaneTable = new javax.swing.JScrollPane();

        jLabelCount1.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jLabelCount1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabelCount1.setText("jLabel1");
        jLabelCount1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

        jSplitPane.setBackground(new java.awt.Color(255, 255, 255));
        jSplitPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jSplitPane.setDividerLocation(100);
        jSplitPane.setForeground(new java.awt.Color(255, 255, 255));
        jSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane.setResizeWeight(1.0);
        jSplitPane.setToolTipText("");
        jSplitPane.setOneTouchExpandable(true);

        jPanel2.setBackground(new java.awt.Color(255, 204, 204));
        jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        jToolBarData.setBackground(new java.awt.Color(255, 204, 204));
        jToolBarData.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jToolBarData.setFloatable(false);
        jToolBarData.setRollover(true);
        jToolBarData.setMaximumSize(new java.awt.Dimension(215, 43));
        jToolBarData.setMinimumSize(new java.awt.Dimension(215, 43));
        jToolBarData.setPreferredSize(new java.awt.Dimension(215, 43));

        jToogleButtonModify.setBackground(new java.awt.Color(255, 204, 204));
        jToogleButtonModify.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jToogleButtonModify.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoModificar.png"))); // NOI18N
        jToogleButtonModify.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jButtonModify.toolTipText"));
        jToogleButtonModify.setFocusable(false);
        jToogleButtonModify.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToogleButtonModify.setIconTextGap(0);
        jToogleButtonModify.setMaximumSize(new java.awt.Dimension(40, 40));
        jToogleButtonModify.setMinimumSize(new java.awt.Dimension(40, 40));
        jToogleButtonModify.setPreferredSize(new java.awt.Dimension(40, 40));
        jToogleButtonModify.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToogleButtonModify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToogleButtonModifyActionPerformed(evt);
            }
        });
        jToolBarData.add(jToogleButtonModify);

        jButtonSave.setBackground(new java.awt.Color(255, 204, 204));
        jButtonSave.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButtonSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoGuardar.png"))); // NOI18N
        jButtonSave.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jButtonSave.toolTipText"));
        jButtonSave.setFocusable(false);
        jButtonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonSave.setIconTextGap(0);
        jButtonSave.setMaximumSize(new java.awt.Dimension(40, 40));
        jButtonSave.setMinimumSize(new java.awt.Dimension(40, 40));
        jButtonSave.setOpaque(false);
        jButtonSave.setPreferredSize(new java.awt.Dimension(40, 40));
        jButtonSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });
        jToolBarData.add(jButtonSave);

        jButtonRemove.setBackground(new java.awt.Color(255, 204, 204));
        jButtonRemove.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButtonRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoBorrar.png"))); // NOI18N
        jButtonRemove.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jButtonRemove.toolTipText"));
        jButtonRemove.setFocusable(false);
        jButtonRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonRemove.setIconTextGap(0);
        jButtonRemove.setMaximumSize(new java.awt.Dimension(40, 40));
        jButtonRemove.setMinimumSize(new java.awt.Dimension(40, 40));
        jButtonRemove.setOpaque(false);
        jButtonRemove.setPreferredSize(new java.awt.Dimension(40, 40));
        jButtonRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveActionPerformed(evt);
            }
        });
        jToolBarData.add(jButtonRemove);

        jTabbedPane.setBackground(new java.awt.Color(245, 244, 236));
        jTabbedPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jTabbedPane.setOpaque(true);
        jScrollPane4.setViewportView(jTabbedPane);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jToolBarData, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jToolBarData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );

        jSplitPane.setRightComponent(jPanel2);

        jPanel1.setBackground(new java.awt.Color(255, 204, 204));

        jToolBar2.setBackground(new java.awt.Color(255, 204, 204));
        jToolBar2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);

        jButtonNew.setBackground(new java.awt.Color(255, 204, 204));
        jButtonNew.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButtonNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoNou.png"))); // NOI18N
        jButtonNew.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jButtonNew.toolTipText"));
        jButtonNew.setAlignmentX(0.5F);
        jButtonNew.setBorder(null);
        jButtonNew.setFocusable(false);
        jButtonNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonNew.setIconTextGap(0);
        jButtonNew.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jButtonNew.setMaximumSize(new java.awt.Dimension(40, 40));
        jButtonNew.setMinimumSize(new java.awt.Dimension(40, 40));
        jButtonNew.setPreferredSize(new java.awt.Dimension(40, 40));
        jButtonNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewActionPerformed(evt);
            }
        });
        jToolBar2.add(jButtonNew);

        jButtonSearch.setBackground(new java.awt.Color(255, 204, 204));
        jButtonSearch.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButtonSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoCercar.png"))); // NOI18N
        jButtonSearch.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jButtonSearch.toolTipText"));
        jButtonSearch.setAlignmentX(0.5F);
        jButtonSearch.setBorder(null);
        jButtonSearch.setFocusable(false);
        jButtonSearch.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonSearch.setIconTextGap(0);
        jButtonSearch.setMaximumSize(new java.awt.Dimension(40, 40));
        jButtonSearch.setMinimumSize(new java.awt.Dimension(40, 40));
        jButtonSearch.setPreferredSize(new java.awt.Dimension(40, 40));
        jButtonSearch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButtonSearch);

        jToogleButtonFilter.setBackground(new java.awt.Color(255, 204, 204));
        jToogleButtonFilter.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jToogleButtonFilter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/xmarti/vacaxm/image/BotoFiltrar.png"))); // NOI18N
        jToogleButtonFilter.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jButtonFilter.toolTipText"));
        jToogleButtonFilter.setAlignmentX(0.5F);
        jToogleButtonFilter.setBorder(null);
        jToogleButtonFilter.setBorderPainted(false);
        jToogleButtonFilter.setFocusable(false);
        jToogleButtonFilter.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToogleButtonFilter.setIconTextGap(0);
        jToogleButtonFilter.setMaximumSize(new java.awt.Dimension(40, 40));
        jToogleButtonFilter.setMinimumSize(new java.awt.Dimension(40, 40));
        jToogleButtonFilter.setPreferredSize(new java.awt.Dimension(40, 40));
        jToogleButtonFilter.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToogleButtonFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToogleButtonFilterActionPerformed(evt);
            }
        });
        jToolBar2.add(jToogleButtonFilter);

        jLabelCount.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        jLabelCount.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabelCount.setText("jLabel1");
        jLabelCount.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPaneTable)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                        .addGap(277, 277, 277)
                        .addComponent(jLabelCount, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelCount, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPaneTable, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE))
        );

        jSplitPane.setLeftComponent(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jSplitPane))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane)
        );
    }// </editor-fold>//GEN-END:initComponents

    
    
   /**
     * Carrega l'objecte
     */
    private void chargeJpAnimalData(){ //carrega les subpantalles, quan sigui el cas caldrà modificar les diferents pantalles
        jTabbedPane.removeAll();      
        if (this.animalClass.equals(Cow.class.getName()) ){            
            jpAnimalData= new JPAnimalData((Cow) this.animal);                
        }else if(this.animalClass.equals(Bull.class.getName()) ){            
            jpAnimalData= new JPAnimalData((Bull)this.animal);
        }else if(this.animalClass.equals(Calf.class.getName()) ){            
            jpAnimalData= new JPAnimalData((Calf)this.animal);
        }
        jTabbedPane.add(jpAnimalData,TDSLanguageUtils.getMessage("jPanelAnimal.jTabbedPane.data.caption"));
        jPanel2.setVisible(true);       
    }
    /**
     * Es dispara al clicar el botó guardar.<br>
     * 1. Guarda l'objecte (saveData de l'objecte)<bR>
     * 2. insereix o modifica l'objecte a la base de dades depenen de l'acció
     * 3. Carrega la base de dades i torna a seleccionar l'objecte
     * @param evt 
     */       
    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        jpAnimalData.saveData();        
        this.handleAction=false;
        this.formatPanel.setFormat();    
        
        try {           
            if(!this.insert){                
                aMaintenance.update(jpAnimalData.getAnimal());
                this.animal= jpAnimalData.getAnimal();
            }
            else {                
                if(aMaintenance.add(jpAnimalData.getAnimal())) {
                    this.insert=false; 
                }                
                if(this.animalClass.equals(Bull.class.getName()) ){
                    this.animals.add((Bull) jpAnimalData.getAnimal());
                    this.animal= (Bull)jpAnimalData.getAnimal();// guarda les dade de l'animal data
                    this.actions.setFathers(true);
                }else if(this.animalClass.equals(Cow.class.getName()) ){                    
                    this.animals.add((Cow) jpAnimalData.getAnimal());
                    this.animal= (Cow)jpAnimalData.getAnimal();// guarda les dade de l'animal data
                    this.actions.setMothers(true);
                }else if(this.animalClass.equals(Calf.class.getName()) ){                                        
                    this.animal= (Calf)jpAnimalData.getAnimal();// guarda les dade de l'animal data
                    this.animals.add((Calf) jpAnimalData.getAnimal());                                         
                }
            }            
            chargeData(jpAnimalData);
            this.saved=true;             
            int i = getSelectedIndex();
            if (i>-1) {
                jTable.setRowSelectionInterval(i, i);
                chargeJpAnimalData();                
            }else {
                jTable.clearSelection(); 
            }
            this.onlyRead=true; 
            this.jToogleButtonModify.setSelected(false);
            enabledObjects();   
            this.formatPanel.chargeFormat();
            this.handleAction=true;
        } catch (ExceptionHibernateVacaxm ex) {
            JOptionPane.showMessageDialog(null,ex.getMessage()+"-"+ jpAnimalData.getAnimal().getId()+"-"+jpAnimalData.getAnimal().toString() ,TDSLanguageUtils.getMessage("save.data.ERR"),JOptionPane.ERROR_MESSAGE);
        }        
    }//GEN-LAST:event_jButtonSaveActionPerformed
    /**
     * Cerca l'objecte actual a la base de dades
     * @return l'index de l'objecte
     */
    private int getSelectedIndex(){ // aqui esta el fallo
        int index=-1;         
        for(int i =0;i< jTable.getRowCount();i++){
            if(jTable.getValueAt(i, 0).toString().equals(this.animal.toString())){ 
                return i;
            } 
        }
        return index; 
    }
    /**
     * Presenta l'objecte
     */
    private void enabledObjects(){
        if (!this.onlyRead){
            jpAnimalData.enabledObjects(true);
            jButtonSave.setEnabled(true);
            jButtonRemove.setEnabled(true);
            jToogleButtonModify.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jToogleButtonModify.notEnabled.toolTipText"));            
            if (!this.insert ){
                jpAnimalData.getjLabelState().setText(TDSLanguageUtils.getMessage("jPanelAnimalData.jLabelState.enabled.text"));
            }else{
                jpAnimalData.getjLabelState().setText(TDSLanguageUtils.getMessage("jPanelAnimalData.jLabelState.new.text"));
            } 
            jpAnimalData.setOpaque(true);
        }else{
            jpAnimalData.enabledObjects(false);
            jButtonSave.setEnabled(false);
            jButtonRemove.setEnabled(false);
            jToogleButtonModify.setToolTipText(TDSLanguageUtils.getMessage("jPanelAnimal.jToogleButtonModify.enabled.toolTipText"));            
            if(this.saved){
                jpAnimalData.getjLabelState().setText(TDSLanguageUtils.getMessage("jPanelAnimalData.jLabelState.notEnabled.saved.text"));
            }else{
                jpAnimalData.getjLabelState().setText(TDSLanguageUtils.getMessage("jPanelAnimalData.jLabelState.notEnabled.text"));
            }
            
            
            jpAnimalData.setOpaque(false);
        }
        jpAnimalData.repaint();
    }
    /**
     * canvia a mode edicio o mode lectura
     * @param evt 
     */
    private void jToogleButtonModifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToogleButtonModifyActionPerformed
        if (!jToogleButtonModify.isSelected()) this.onlyRead=true; 
        else  this.onlyRead=false;
        enabledObjects();
    }//GEN-LAST:event_jToogleButtonModifyActionPerformed

    private void jToogleButtonFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToogleButtonFilterActionPerformed
       if(jToogleButtonFilter.isSelected()){
           JDFilterAnimal dialog = new JDFilterAnimal(new javax.swing.JFrame(), true);
           dialog.setLocationRelativeTo(null);
           dialog.setVisible(true);
           this.animalFilter=dialog.getAnimalFilter();
       }else{
           this.animalFilter=new AnimalFilter(); 
       }
        try {
            this.chargeData(null);
        } catch (ExceptionHibernateVacaxm ex) {
            Logger.getLogger(JPAnimal.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }//GEN-LAST:event_jToogleButtonFilterActionPerformed
    
    /**
     * Presenta un nou registre
     * @param evt 
     */
    private void jButtonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewActionPerformed
        this.insert=true;
        //jTabbedPane.removeAll();   
        this.handleAction=false;
        this.formatPanel.setFormat(); 
        
        if(this.animalClass.equals(Cow.class.getName()) ){
            this.animal=new Cow();        
          //  jpAnimalData= new JPAnimalData((Cow) this.animal);
        }else if(this.animalClass.equals(Bull.class.getName()) ){
            this.animal=new Bull();        
            //jpAnimalData= new JPAnimalData((Bull) this.animal);  
        }else if(this.animalClass.equals(Calf.class.getName()) ){            
            this.animal=new Calf(this.gender.getGender());              
        }       
        
        this.chargeJpAnimalData();        
        this.onlyRead=false; 
        if(!jToogleButtonModify.isSelected()) jToogleButtonModify.setSelected(true);      
        enabledObjects();                
        jTable.clearSelection(); 
        this.formatPanel.chargeFormat();
        this.handleAction=true;
    }//GEN-LAST:event_jButtonNewActionPerformed
    
    private void selectionEvent(ListSelectionEvent e){             
        if(this.jTable.getSelectedRow()>-1){                                  
           if(this.handleAction)    formatPanel.setFormat();
                 this.animal=(Animal) this.jTable.getValueAt(this.jTable.getSelectedRow(),0); 
                if (this.animal.getId()==-1) {
                    this.insert=true;
                    this.onlyRead=false;
                    this.jToogleButtonModify.setSelected(true);
                } else{
                    this.insert=false; 
                    this.onlyRead=true; 
                    jToogleButtonModify.setSelected(false);
                }                
                chargeJpAnimalData();   
                this.jTable.setScroll();                
                enabledObjects();
        }                                                         
        if(this.handleAction)    formatPanel.chargeFormat();
   }
       
    private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButtonRemoveActionPerformed
    /**
     * Crea el model de dades
     * @return 
     */
    private TableModel getModel() throws ExceptionHibernateVacaxm{        
        DateFormat df = new SimpleDateFormat("dd-MM-YYYY");
        TableModel dadesTaula = null;        
        if (this.animalClass.equals(Bull.class.getName())){
            this.animals=(List<Bull>)this.aMaintenance.getBullsActive(animalFilter);                          
            String [] columns={TDSLanguageUtils.getMessage("jPanelAnimal.JTable.name.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.identification.caption"),                        
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.age.year.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.dateHigh.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.dateLow.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.father.caption"), 
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.mother.caption"),
                          };    
            Object[][] dades=null;
            if (this.animals.size()==0){
                dades=new Object[1][columns.length];                          
                dades[0][0]=new Bull();
                dades[0][1]="-";
                dades[0][2]="-";
                dades[0][3]="-";
                dades[0][4]="-";
                dades[0][5]="-";                
                dades[0][6]="-";
            }
            else{
                dades=new Object[this.animals.size()][columns.length];                          
                Integer i=0;            
                for (Iterator it = this.animals.iterator(); it.hasNext();) {
                    Bull c = (Bull) it.next();                
                    dades[i][0]=(AnimalCode) c;
                    if (c.getName()==(null))dades[i][1]="-"; else dades[i][1]=c.getCodeAnimalToString();
                    dades[i][2]=c.getAge()/365;
                    if (c.getHighDate()==(null))dades[i][3]="-"; else dades[i][3]=df.format(c.getHighDate());
                    if (c.getLowDate()==(null))dades[i][4]="-"; else dades[i][4]=df.format(c.getLowDate());
                    if (c.getFather()==(null))dades[i][5]= "-"; else dades[i][5]=c.getFather().toString();
                    if (c.getMother()==(null))dades[i][6]= "-"; else dades[i][6]=c.getMother().toString();                
                    i++;
                }     
            }
                
            dadesTaula=new TableModel(columns, dades);                       
        }else if (this.animalClass.equals(Cow.class.getName())){
            this.animals=(List<Cow>)this.aMaintenance.getCowsActive(animalFilter);                          
            String [] columns={
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.identification.caption"),  
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.age.year.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.dateHigh.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.dateLow.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.father.caption"), 
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.mother.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.state.caption")};        
            Object[][] dades=null;
            if (this.animals.size()==0){
                dades=new Object[1][columns.length];                          
                dades[0][0]=new Cow();
                dades[0][1]="-";
                dades[0][2]="-";
                dades[0][3]="-";
                dades[0][4]="-";
                dades[0][5]="-";                
                dades[0][6]="-";
            }else{
            dades=new Object[this.animals.size()][columns.length];                          
            Integer i=0;
            for (Iterator it = this.animals.iterator(); it.hasNext();) {
                Cow c = (Cow)it.next();
                if (i<this.animals.size()){                    
                    dades[i][0]=(AnimalCode) c;                    
                    dades[i][1]=c.getAge()/365;
                    if (c.getHighDate()==(null))dades[i][2]="-"; else dades[i][2]=df.format(c.getHighDate());                
                    if (c.getLowDate()==(null))dades[i][3]="-"; else dades[i][3]=df.format(c.getLowDate());
                    if (c.getFather()==(null))dades[i][4]= "-"; else dades[i][4]=c.getFather().toString();
                    if (c.getMother()==(null))dades[i][5]= "-"; else dades[i][5]=c.getMother().toString();
                    dades[i][6]=c.isActive();
                }
                i++;
                }    
            }                            
            dadesTaula=new TableModel(columns, dades);                       
        }else if (this.animalClass.equals(Calf.class.getName())){
            this.animals=(List<Calf>)this.aMaintenance.getCalfsActive(this.animalFilter,this.gender.getGender());                          
            String [] columns={
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.identification.caption"),  
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.age.month.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.dateHigh.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.dateLow.caption"),
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.father.caption"), 
                          TDSLanguageUtils.getMessage("jPanelAnimal.JTable.mother.caption")
                          };        
            
            Object[][] dades=null;
            if (this.animals.size()==0){
                dades=new Object[1][columns.length];                          
                dades[0][0]=new Calf(this.gender.getGender());
                dades[0][1]="-";
                dades[0][2]="-";
                dades[0][3]="-";
                dades[0][4]="-";
                dades[0][5]="-";                
               
            }else{
                dades=new Object[this.animals.size()][columns.length];                                      
                Integer i=0;
                for (Iterator it = this.animals.iterator(); it.hasNext();) {
                    Calf c = (Calf)it.next();
                    dades[i][0]=(AnimalCode) c;                
                    dades[i][1]=c.getAge()/30;
                    if (c.getHighDate()==(null))dades[i][2]="-"; else dades[i][2]=df.format(c.getHighDate());
                    if (c.getLowDate()==(null))dades[i][3]="-"; else dades[i][3]=df.format(c.getLowDate());
                    if (c.getFather()==(null))dades[i][4]= "-"; else dades[i][4]=c.getFather().toString();
                    if (c.getMother()==(null))dades[i][5]= "-"; else dades[i][5]=c.getMother().toString();
                    i++;
                }            
            }
            dadesTaula=new TableModel(columns, dades);                       
        }
        
        return dadesTaula;        
    }
    
    @Override
    public String toString(){
        return "JPANIMAL";
    }
            
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonNew;
    private javax.swing.JButton jButtonRemove;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JLabel jLabelCount;
    private javax.swing.JLabel jLabelCount1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPaneTable;
    private javax.swing.JSplitPane jSplitPane;
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JToggleButton jToogleButtonFilter;
    private javax.swing.JToggleButton jToogleButtonModify;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JToolBar jToolBarData;
    // End of variables declaration//GEN-END:variables

    @Override
    public void updateMother() {
       if(this.jpAnimalData!=null) this.jpAnimalData.chargeCows();
    }

    @Override
    public void updateFather() {
        if(this.jpAnimalData!=null) this.jpAnimalData.chargeBulls();
    }

    @Override
    public void updateOrigin() {
        if(this.jpAnimalData!=null) this.jpAnimalData.chargeOrigins();
    }

    @Override
    public void updateDestination() {
        if(this.jpAnimalData!=null) this.jpAnimalData.chargeDestinations();
    }

   

}

